import type { Request, Response, NextFunction } from 'express';
import { AppDataSource } from '@/data-source';
import {
  responseError,
  responseSuccess,
  responseData,
} from '@/share/interface/standard';
import { User, ModuleClick } from '@/entity/miniProgram/User';
import { IModule } from '@/share/interface/module';

const addModuleClick = async ({
  user_id,
  module_name,
}: {
  user_id: number;
  module_name: string;
}) => {
  const userRepository = AppDataSource.getRepository(User);
  const moduleClickRepository =
    AppDataSource.getRepository(ModuleClick);
  const user = await userRepository.findOne({
    where: {
      id: user_id,
    },
    relations: ['module_data'],
  });

  if (!user) {
    return responseData({ code: 201, msg: '用户不存在', data: null });
  }
  if (!Object.values(IModule).includes(module_name)) {
    throw '模块不存在';
  }
  const module = await moduleClickRepository.findOne({
    where: {
      user: { id: user.id },
      module_name,
    },
  });
  await moduleClickRepository.save({
    id: module?.id,
    user,
    module_name,
    module_visit: module?.module_visit + 1 || 1,
  });
  return responseSuccess(module_name + '模块信息添加成功');
};
export const moduleClickMiddleware = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  req.addModuleClick = addModuleClick; // 将addModuleClick方法挂载到req上
  next(); // 确保调用下一个中间件或路由处理函数
};
